# -*- encoding=utf8 -*-
import subprocess, time, os
from datetime import datetime
from airtest.core.api import keyevent, touch, auto_setup, snapshot
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from airtest.core.api import log, auto_setup
from airtest.report.report import simple_report

class PocoApi:
    poco = None

    # 内置函数
    def __init__(self):
        PocoApi.poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
        # 项目目录
        self.base_path = os.path.split(os.path.dirname(__file__))[0]
        # auto_setup(__file__, logdir=f"{self.base_path}/AirTestLog")  # 设置日志目录

        log_interceptor = open(self.base_path + '/interface/log_interceptor.txt', 'w')
        command = [
            "mitmdump",  # 用于拦截、查看和修改HTTP/HTTPS流量。
            "-p", "8888",  # 指定了代理服务器监听的端口号
            "--ssl-insecure",  # 允许不安全的 SSL 连接。
            "-s", self.base_path + '/interface/SaveResponse.py',
        ]
        PocoApi.child = subprocess.Popen(
            command,
            stdout=log_interceptor
        )
        self.init_file()
        print(".....start.....")
    def __del__(self):
        # simple_report(__file__, logpath=True, logfile=f"{self.base_path}/AirTestLog/log.txt",
        #               output=f"{self.base_path}/AirTestLog/log.html")
        print(".....end.....")
    # 初始化文件夹
    def init_file(self):
        if os.path.exists(self.base_path + "/interface/response"):
            if os.path.isfile(self.base_path + "/interface/response/filtered_responses.json"):
                os.remove(self.base_path + "/interface/response/filtered_responses.json")
            if os.path.isfile(self.base_path + "/interface/response/finish.json"):
                os.remove(self.base_path + "/interface/response/finish.json")
        else:
            os.makedirs(self.base_path + "/interface/response", exist_ok=True)
        if not os.path.isfile(self.base_path + "/interface/log_interceptor.txt"):
            with open(self.base_path + "/interface/log_interceptor.txt", 'rb') as f:
                f.write("")

    # 杀死进程
    def close_child(self):
        self.child.kill()
        print("子进程已关闭")

    def poco_click(self, sel=None, **kwargs):
        try:
            if 'text' in kwargs:
                element = self.poco(text=kwargs['text'])
                element.click()
                element_text = element.get_text()  # 获取元素的文本内容
                print(f"成功点击元素：{kwargs['text']}")
                log(f"成功点击元素：{kwargs['text']}, 元素文本：{element_text}",timestamp=time.time(), desc="点击操作", snapshot=True)
                return element_text  # 返回文本内容
            else:
                element = self.poco(sel)
                element.click()
                element_text = element.get_text()  # 获取元素的文本内容
                print(f"成功点击元素：{sel}")
                log(f"成功点击元素：{sel}, 元素文本：{element_text}",timestamp=time.time(), desc="点击操作", snapshot=True)
                return element_text  # 返回文本内容
        except Exception as e:
            print(f"点击元素失败：{sel if 'text' not in kwargs else kwargs['text']}, 错误信息：{e}")
            log(f"点击元素失败：{sel if 'text' not in kwargs else kwargs['text']}, 错误信息：{e}",timestamp=time.time(), desc="获取不到点击按钮", snapshot=True)

    def poco_click_name_test(self, name, text):
        try:
            self.poco(name=name, text=text).click()
            print(f"成功点击元素：{name}, 文本：{text}")
            log(f"成功点击元素：{name}, 文本：{text}",timestamp=time.time(), desc="点击操作(元素name与text)", snapshot=True)
        except Exception as e:
            print(f"点击元素失败：{name}, 文本：{text}, 错误信息：{e}")
            log(f"点击元素失败：{name}, 文本：{text}, 错误信息：{e}",timestamp=time.time(), desc="获取不到点击按钮(元素name与text)", snapshot=True)

    def poco_text(self, sel, text):
        try:
            self.poco(sel).set_text(text)
            print(f"成功输入文本：{text}")
            log(f"输入文本成功：{text}")
        except Exception as e:
            print(f"输入文本失败：{text}, 错误信息：{e}")
            log(f"输入文本失败：{text}, 错误信息：{e}")

    def poco_exists(self, sel):
        try:
            if self.poco(sel).exists():
                print(f"元素{sel}存在")
                log(f"元素{sel}存在",timestamp=time.time(), desc=f"元素{sel}存在", snapshot=True)
                return True
            else:
                print(f"元素{sel}不存在")
                log(f"元素{sel}不存在",timestamp=time.time(), desc=f"元素{sel}不存在", snapshot=True)
                return False
        except Exception as e:
            print(f"元素{sel}不存在")
            log(e,timestamp=time.time(), desc=f"元素{sel}存在", snapshot=True)

    def poco_click_text(self, text):
        try:
            self.poco(text).click()
            print(f"成功点击文本：{text}")
            log(f"成功点击文本：{text}")
        except Exception as e:
            print(f"点击文本失败：{text}, 错误信息：{e}")
            log(f"点击文本失败：{text}, 错误信息：{e}")

    def poco_click_index(self, sel, index):
        try:
            self.poco(sel)[index].click()
            print(f"成功点击元素：{sel}, 下标：{index}")
            log(f"成功点击元素：{sel}, 下标：{index}")
        except Exception as e:
            print(f"点击元素失败：{sel}, 下标：{index}, 错误信息：{e}")
            log(f"点击元素失败：{sel}, 下标：{index},错误信息：{e}")

    def poco_click_text_index(self, text, index):
        try:
            self.poco(text)[index].click()
            print(f"成功点击文本：{text}, 下标：{index}")
            log(f"成功点击文本：{text}, 下标：{index}")
        except Exception as e:
            print(f"点击文本失败：{text}, 下标：{index}, 错误信息：{e}")
            log(f"点击文本失败：{text}, 下标：{index}, 错误信息：{e}")

    def poco_wait(self, sel, timeout=10):
        try:
            self.poco(sel).wait_for_appearance(timeout=timeout)
            print(f"元素{sel}出现")
            log(f"元素{sel}出现")
        except Exception as e:
            print(f"元素{sel}未出现")
            log(f"元素{sel}未出现")

    def poco_home(self):
        keyevent("HOME")
        log("HOME")

    def poco_back(self):
        keyevent("BACK")
        log("BACK")

    def poco_swipe(self, start, end, duration=0.5):
        try:
            self.poco.swipe(start, end, duration=duration)
            print(f"成功滑动")
            log(f"成功滑动")
        except Exception as e:
            print(f"滑动失败，错误信息：{e}")
            log(f"滑动失败，错误信息：{e}")

    def poco_touch(self, x, y):
        try:
            touch((x, y))  # 使用 Airtest 的 touch 方法
            print(f"成功点击坐标：{x},{y}")
            log(f"成功点击坐标：{x},{y}")
        except Exception as e:
            print(f"点击坐标失败：{x},{y}, 错误信息：{e}")
            log(f"点击坐标失败：{x},{y}, 错误信息：{e}")

    def poco_skip_ad(self):
        try:
            if self.poco("android.widget.FrameLayout").child("android.view.View").child("android.view.View").child(
                    "android.widget.ImageView").wait(timeout=5).exists():
                self.poco("android.widget.FrameLayout").child("android.view.View").child("android.view.View").child(
                    "android.widget.ImageView").click()
            else:
                print("无广告")
                log("无广告")
        except Exception as e:
            print("跳过广告失败，错误信息：", e)
            log("跳过广告失败，错误信息：", e)

    def poco_snapshot(self):
        snapshot("test_snapshot.png", msg="这是一张测试截图")
